package com.caimiao.miao.library.utils.storage;

import android.content.Context;
import android.os.Environment;

import com.caimiao.miao.library.utils.sys.NetUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.io.Writer;

public class FileUtil {
    /**
     * 读取固定的文件中的内容
     *
     * @return
     */
    public static String read(String fileDir, String fileName) {
        File file = getFile(fileDir, fileName);
        StringBuffer buffer = new StringBuffer();
        FileInputStream fis = null;
        InputStreamReader isr = null;
        Reader in = null;
        try {
            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis, "UTF-8");
            in = new BufferedReader(isr);
            int i;
            while ((i = in.read()) > -1) {
                buffer.append((char) i);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) fis.close();
                if (isr != null) isr.close();
                if (in != null) in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return buffer.toString();
    }


    /**
     * 保存内容
     *
     * @param str
     */
    public static File save(String str, String fileDir, String fileName) {
        File file = getFile(fileDir, fileName);
        FileOutputStream fos = null;
        Writer out = null;
        try {
            fos = new FileOutputStream(file);
            out = new OutputStreamWriter(fos, "UTF-8");
            out.write(str);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) fos.close();
                if (out != null) out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    public static File saveByAppend(String str, String fileDir, String fileName) {
        File file = getFile(fileDir, fileName);
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(file, "rw");
            raf.seek(file.length());//在原来的基础上继续写
            raf.write(str.getBytes("UTF-8"));

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }

    /**
     * 统一处理设备唯一标识 保存的文件的地址
     *
     * @return
     */
    private static File getFile(String fileDir, String fileName) {
        File dir = getExternalFileDir(fileDir);
        if (dir == null) return null;
        File file = new File(dir, fileName);
        return file;
    }

    /***********************************获取对应目录的文件对象**********************************/

    /**
     * 判断是否有外置SD卡
     */
    public static Boolean existsSdcard() {
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable();
    }

    /**
     * 获取应用对应的扩展存储目录--缓存目录下的指定目录
     *
     * @param context
     * @param dirName 指定目录名称
     * @return
     */
    public static File getDiskCacheDir(Context context, String dirName) {
        String dir = String.format("%s/%s/", getDiskCacheRootDir(context), dirName);
        File file = new File(dir);
        if (!file.exists()) {
            file.mkdirs();
        }
        return file;
    }

    /**
     * 获取应用对应的扩展存储目录--文件目录下的指定目录
     *
     * @param context
     * @param dirName 指定目录名称
     * @return
     */
    public static File getDiskFileDir(Context context, String dirName) {
        String dir = String.format("%s/%s/", getDiskFileRootDir(context), dirName);
        File file = new File(dir);
        if (!file.exists()) {
            file.mkdirs();
        }
        return file;
    }

    /**
     * 获取应用对应的扩展存储目录--缓存目录
     *
     * @param context
     * @return
     */
    public static File getDiskCacheRootDir(Context context) {
        File diskRootFile;
        if (existsSdcard()) {
            diskRootFile = context.getExternalCacheDir();
            //应用在外部存储中的cache路径
            //一般为： /storage/emulated/0/Android/data/packname/cache
        } else {
            diskRootFile = context.getCacheDir();
            //应用在内部存储中的cache路径
            //一般为：/data/user/0/packname/cache
        }
        if (diskRootFile == null) {
            throw new IllegalArgumentException("disk is invalid");
        }
        return diskRootFile;
    }


    /**
     * 获取应用对应的扩展存储目录--文件目录
     *
     * @param context
     * @return
     */
    public static File getDiskFileRootDir(Context context) {
        File diskRootFile;
        if (existsSdcard()) {
            diskRootFile = context.getExternalFilesDir(null);
            //应用在外部存储中的files路径
            //一般为：/storage/emulated/0/Android/data/packname/files
        } else {
            diskRootFile = context.getFilesDir();
            //应用在内部存储中的files路径
            //一般为： /data/user/0/packname/files
        }
        if (diskRootFile == null) {
            throw new IllegalArgumentException("disk is invalid");
        }
        return diskRootFile;
    }

    /**
     * 获取应用对应的扩展存储目录--自定义文件目录
     *
     * @param context
     * @param dirName
     * @return
     */
    public static File getDiskDir(Context context, String dirName) {
        File diyFile = context.getDir(dirName, Context.MODE_PRIVATE);
        //应用在内部存储中的dirName路径
        //一般为： /data/user/0/packname/dirName
        if (diyFile == null) {
            throw new IllegalArgumentException("disk is invalid");
        }
        return diyFile;
    }

    /**
     * 获取外部存储根目录下的指定目录
     * 外置SD卡我们则需要通过getExternalDirs遍历来获取
     *
     * @param dirName 指定目录
     * @return
     */
    public static File getExternalFileDir(String dirName) {
        if (!existsSdcard()) {
            return null;
        }
        String dir = String.format("%s/%s/", Environment.getExternalStorageDirectory().toString(), dirName);
        //获取外部存储的根路径
        //一般为： /storage/emulated/0
        File fileDir = new File(dir);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        return fileDir;
    }

    public static File getSystemFileDir() {
        File file = Environment.getRootDirectory();
        //Android系统的“System”分区的根目录
        //一般为：/system
        return file;
    }
}
